package com.tangyh.lamp.common.util;

import com.tangyh.basic.base.constant.StringPool;
import com.tangyh.basic.utils.CommonUtil;
import com.tangyh.basic.utils.DateUtils;
import lombok.NonNull;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

/**
 * 日期工具类
 *
 */
public class BaseDateUtil extends DateUtils{
    public static final String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
    public static final String DATE_PATTERN = "yyyy-MM-dd";
    public static final String DATE_PATTERN_CLEAR = "yyyyMMdd";
    public static final String DATE_TIME_PATTERN_CLEAR = "yyyyMMdd HHmmss";
    public static final String DATE_YEAR_MONTH_PATTERN_CLEAR = "yyyy-MM";


    /**
     * 将日期解析成指定格式，会根据传入类型使用 instanceof 判断类型
     *
     * @param dateTime 本地日期和时间
     * @param pattern  日期解析格式
     * @return 指定日期解析结果
     */
    public static String getDateTime(@NonNull Object dateTime, String pattern) {
        if (dateTime instanceof Date) {
            return getDateTime((Date) dateTime, pattern);
        } else if (dateTime instanceof LocalDateTime) {
            return getDateTime((LocalDateTime) dateTime, pattern);
        }
        return StringPool.EMPTY;
    }

    /**
     * 获取本地日期对象
     * 默认格式：yyyy-MM-dd
     *
     * @param date 日期字符串
     * @return 返回LocalDate对象，格式为2020-02-02
     */
    public static LocalDate getLocalDate(String date) {
        return getLocalDate(date, StringPool.EMPTY);
    }

    /**
     * 获取本地日期对象
     *
     * @param date    日期字符串
     * @param pattern 日期解析格式
     * @return 返回LocalDate对象
     */
    public static LocalDate getLocalDate(String date, String pattern) {
        if (CommonUtil.isEmpty(pattern)) {
            pattern = DATE_PATTERN;
        }
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
        return LocalDate.parse(date, dateTimeFormatter);
    }

    /**
     * 获取本地日期时间对象，字符串转LocalDateTime
     * 默认格式：yyyy-MM-dd HH:mm:ss
     *
     * @param dateTime 日期时间字符串，为空返回当前时间
     * @return 返回LocalDate对象，格式为2020-02-02 15:12:12
     */
    public static LocalDateTime getLocalDateTime(String dateTime) {
        if (dateTime == null) {
            return LocalDateTime.now();
        }
        return getLocalDateTime(dateTime, StringPool.EMPTY);
    }

    /**
     * 获取本地日期时间对象
     *
     * @param dateTime 日期时间字符串，为空返回当前时间
     * @param pattern  日期解析格式
     * @return 返回LocalDate对象
     */
    public static LocalDateTime getLocalDateTime(String dateTime, String pattern) {
        if (dateTime == null) {
            return LocalDateTime.now();
        }
        if (CommonUtil.isEmpty(pattern)) {
            pattern = DATE_TIME_PATTERN;
        }
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
        return LocalDateTime.parse(dateTime, dateTimeFormatter);
    }

    /**
     * 按照指定日期格式解析当前时间
     *
     * @param pattern 日期解析格式
     * @return 当前日期
     */
    public static String getDateTime(String pattern) {
        if (CommonUtil.isEmpty(pattern)) {
            pattern = DATE_TIME_PATTERN;
        }
        return new SimpleDateFormat(pattern).format(new Date());
    }

    /**
     * 将指定日期解析成指定格式
     *
     * @param date    日期
     * @param pattern 日期解析格式
     * @return 指定日期解析结果
     */
    public static String getDateTime(@NonNull Date date, String pattern) {
        if (CommonUtil.isEmpty(pattern)) {
            pattern = DATE_TIME_PATTERN;
        }
        return new SimpleDateFormat(pattern).format(date);
    }

    public static String getDateTime(@NonNull Date date) {
        return getDateTime(date, DATE_TIME_PATTERN);
    }

    /**
     * 将指定日期解析成指定格式
     *
     * @param localDateTime 本地日期和时间
     * @param pattern       日期解析格式
     * @return 指定日期解析结果
     */
    public static String getDateTime(@NonNull LocalDateTime localDateTime, String pattern) {
        if (CommonUtil.isEmpty(pattern)) {
            pattern = DATE_TIME_PATTERN;
        }
        return localDateTime.format(DateTimeFormatter.ofPattern(pattern));
    }

    public static String getDateTime(@NonNull LocalDateTime localDateTime) {
        return getDateTime(localDateTime, DATE_TIME_PATTERN);
    }

    public static String getDateTime(@NonNull LocalDate localDate) {
        return getDateTime(localDate, DATE_PATTERN);
    }


    /**
     * 获取当天开始时间
     * 例子：2020-04-17T00:00
     *
     * @return
     */
    public static LocalDateTime getDayStartTime() {
        return LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
    }

    /**
     * 获取当天结束时间
     * 例子：2020-04-17T23:59:59.999999999
     *
     * @return
     */
    public static LocalDateTime getDayEndTime() {
        return LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
    }


    /**
     * 获取当月开始时间
     * 例子：2020-04-01T00:00
     *
     * @return
     */
    public static LocalDateTime getMonthStartTime() {
        return LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfMonth()), LocalTime.MIN);
    }

    /**
     * 获取当月结束时间
     * 例子：2020-04-30T23:59:59.999999999
     *
     * @return
     */
    public static LocalDateTime getMonthEndTime() {
        return LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.lastDayOfMonth()), LocalTime.MAX);
    }

    /**
     * 获取指定时间月开始时间
     * 例子：2020-04-01T00:00
     *
     * @return
     */
    public static LocalDateTime getMonthStartTime(LocalDate now) {
        return LocalDateTime.of(now.with(TemporalAdjusters.firstDayOfMonth()), LocalTime.MIN);
    }

    /**
     * 获取指定时间月结束时间
     * 例子：2020-04-30T23:59:59.999999999
     *
     * @return
     */
    public static LocalDateTime getMonthEndTime(LocalDate now) {
        return LocalDateTime.of(now.with(TemporalAdjusters.lastDayOfMonth()), LocalTime.MAX);
    }

    /**
     * 获取今年开始时间
     * 例子：2020-01-01T00:00
     *
     * @return
     */
    public static LocalDateTime getYearStartTime() {
        return LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfYear()), LocalTime.MIN);
    }

    /**
     * 获取今年结束时间
     * 例子：2020-12-31T23:59:59.999999999
     *
     * @return
     */
    public static LocalDateTime getYearEndTime() {
        return LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.lastDayOfYear()), LocalTime.MAX);
    }


    /* ########### ###################其他*/

    public static Date parseDate(String date, String pattern) {
        if (pattern == null || pattern.equals("")) {
            pattern = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        try {
            return (sdf.parse(date));
        } catch (ParseException e) {
            e.printStackTrace();
            return (null);
        }
    }

    public static String formatDate(Date date, String pattern) {
        if (pattern == null || pattern.equals("")) {
            pattern = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return (sdf.format(date));
    }

    //获取当天的开始时间
    public static Date getDayBegin() {
        Calendar cal = new GregorianCalendar();
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime();
    }

    //获取当天的结束时间
    public static Date getDayEnd() {
        Calendar cal = new GregorianCalendar();
        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        return cal.getTime();
    }

    //获取昨天的开始时间
    public static Date getBeginDayOfYesterday() {
        Calendar cal = new GregorianCalendar();
        cal.setTime(getDayBegin());
        cal.add(Calendar.DAY_OF_MONTH, -1);
        return cal.getTime();
    }

    //获取昨天的结束时间
    public static Date getEndDayOfYesterDay() {
        Calendar cal = new GregorianCalendar();
        cal.setTime(getDayEnd());
        cal.add(Calendar.DAY_OF_MONTH, -1);
        return cal.getTime();
    }

    //获取明天的开始时间
    public static Date getBeginDayOfTomorrow() {
        Calendar cal = new GregorianCalendar();
        cal.setTime(getDayBegin());
        cal.add(Calendar.DAY_OF_MONTH, 1);

        return cal.getTime();
    }

    //获取明天的结束时间
    public static Date getEndDayOfTomorrow() {
        Calendar cal = new GregorianCalendar();
        cal.setTime(getDayEnd());
        cal.add(Calendar.DAY_OF_MONTH, 1);
        return cal.getTime();
    }

    //获取本周的开始时间
    public static Date getBeginDayOfWeek() {
        Date date = new Date();
        if (date == null) {
            return null;
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int dayofweek = cal.get(Calendar.DAY_OF_WEEK);
        if (dayofweek == 1) {
            dayofweek += 7;
        }
        cal.add(Calendar.DATE, 2 - dayofweek);
        return getDayStartTime(cal.getTime());
    }

    //获取本周的结束时间
    public static Date getEndDayOfWeek() {
        Calendar cal = Calendar.getInstance();
        cal.setTime(getBeginDayOfWeek());
        cal.add(Calendar.DAY_OF_WEEK, 6);
        Date weekEndSta = cal.getTime();
        return getDayEndTime(weekEndSta);
    }

    //获取本月的开始时间
    public static Date getBeginDayOfMonth() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(getNowYear(), getNowMonth() - 1, 1);
        return getDayStartTime(calendar.getTime());
    }

    //获取本月的结束时间
    public static Date getEndDayOfMonth() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(getNowYear(), getNowMonth() - 1, 1);
        int day = calendar.getActualMaximum(5);
        calendar.set(getNowYear(), getNowMonth() - 1, day);
        return getDayEndTime(calendar.getTime());
    }

    //获取上个月的开始时间
    public static Date getBeforeBeginDayOfMonth() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -1);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        return getDayEndTime(calendar.getTime());
    }

    //获取上个月的结束时间
    public static Date getBeforeEndDayOfMonth() {
        Calendar calendar = Calendar.getInstance();
        int month = calendar.get(Calendar.MONTH);
        calendar.set(Calendar.MONTH, month - 1);
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        return getDayEndTime(calendar.getTime());
    }

    //获取本年的开始时间
    public static Date getBeginDayOfYear() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, getNowYear());
        // cal.set
        cal.set(Calendar.MONTH, Calendar.JANUARY);
        cal.set(Calendar.DATE, 1);

        return getDayStartTime(cal.getTime());
    }

    //获取本年的结束时间
    public static Date getEndDayOfYear() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, getNowYear());
        cal.set(Calendar.MONTH, Calendar.DECEMBER);
        cal.set(Calendar.DATE, 31);
        return getDayEndTime(cal.getTime());
    }

    //获取某个日期的开始时间
    public static Timestamp getDayStartTime(Date d) {
        Calendar calendar = Calendar.getInstance();
        if (null != d) {
            calendar.setTime(d);
        }
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 0,
                0, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return new Timestamp(calendar.getTimeInMillis());
    }

    //获取某个日期的结束时间
    public static Timestamp getDayEndTime(Date d) {
        Calendar calendar = Calendar.getInstance();
        if (null != d) {
            calendar.setTime(d);
        }
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 23,
                59, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        return new Timestamp(calendar.getTimeInMillis());
    }

    //获取今年是哪一年
    public static Integer getNowYear() {
        Date date = new Date();
        GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
        gc.setTime(date);
        return Integer.valueOf(gc.get(1));
    }

    //获取本月是哪一月
    public static int getNowMonth() {
        Date date = new Date();
        GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
        gc.setTime(date);
        return gc.get(2) + 1;
    }

    /**
     * 39      * 日期加上天数后的日期
     * 40      * @param num 为增加的天数
     * 40      * @param date 日期
     * 41      * @return
     * 42
     */
    public static Date plusDay(long num, Date date) {
        long time = date.getTime(); // 得到指定日期的毫秒数
        num = num * 24 * 60 * 60 * 1000; // 要加上的天数转换成毫秒数
        time += num; // 相加得到新的毫秒数
        return new Date(time);
    }

    //两个日期相减得到的天数
    public static long getDiffDays(Date beginDate, Date endDate) {

        if (beginDate == null || endDate == null) {
            throw new IllegalArgumentException("getDiffDays param is null!");
        }

        long days = (endDate.getTime() - beginDate.getTime()) / (1000 * 60 * 60 * 24);

//        int days = new Long(diff).intValue();

        return days;
    }

    //两个日期相减得到的毫秒数
    public static long dateDiff(Date beginDate, Date endDate) {
        long date1ms = beginDate.getTime();
        long date2ms = endDate.getTime();
        return date2ms - date1ms;
    }

    //获取两个日期中的最大日期
    public static Date max(Date beginDate, Date endDate) {
        if (beginDate == null) {
            return endDate;
        }
        if (endDate == null) {
            return beginDate;
        }
        if (beginDate.after(endDate)) {
            return beginDate;
        }
        return endDate;
    }

    //获取两个日期中的最小日期
    public static Date min(Date beginDate, Date endDate) {
        if (beginDate == null) {
            return endDate;
        }
        if (endDate == null) {
            return beginDate;
        }
        if (beginDate.after(endDate)) {
            return endDate;
        }
        return beginDate;
    }

    //返回某月该季度的第一个月
    public static Date getFirstSeasonDate(Date date) {
        final int[] SEASON = {1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4};
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int sean = SEASON[cal.get(Calendar.MONTH)];
        cal.set(Calendar.MONTH, sean * 3 - 3);
        return cal.getTime();
    }

    //返回某个日期下几天的日期
    public static Date getNextDay(Date date, int i) {
        Calendar cal = new GregorianCalendar();
        cal.setTime(date);
        cal.set(Calendar.DATE, cal.get(Calendar.DATE) + i);
        return cal.getTime();
    }

    //返回某个日期前几天的日期
    public static Date getFrontDay(Date date, int i) {
        Calendar cal = new GregorianCalendar();
        cal.setTime(date);
        cal.set(Calendar.DATE, cal.get(Calendar.DATE) - i);
        return cal.getTime();
    }

    //获取某年某月到某年某月按天的切片日期集合（间隔天数的日期集合）
    public static List getTimeList(int beginYear, int beginMonth, int endYear, int endMonth, int k) {
        List list = new ArrayList();
        if (beginYear == endYear) {
            for (int j = beginMonth; j <= endMonth; j++) {
                list.add(getTimeList(beginYear, j, k));

            }
        } else {
            {
                for (int j = beginMonth; j < 12; j++) {
                    list.add(getTimeList(beginYear, j, k));
                }

                for (int i = beginYear + 1; i < endYear; i++) {
                    for (int j = 0; j < 12; j++) {
                        list.add(getTimeList(i, j, k));
                    }
                }
                for (int j = 0; j <= endMonth; j++) {
                    list.add(getTimeList(endYear, j, k));
                }
            }
        }
        return list;
    }

    //获取某年某月按天切片日期集合（某个月间隔多少天的日期集合）
    public static List getTimeList(int beginYear, int beginMonth, int k) {
        List list = new ArrayList();
        Calendar begincal = new GregorianCalendar(beginYear, beginMonth, 1);
        int max = begincal.getActualMaximum(Calendar.DATE);
        for (int i = 1; i < max; i = i + k) {
            list.add(begincal.getTime());
            begincal.add(Calendar.DATE, k);
        }
        begincal = new GregorianCalendar(beginYear, beginMonth, max);
        list.add(begincal.getTime());
        return list;
    }

    // 获取某年某月 所有日期（yyyy-mm-dd格式字符串）
    public static List<String> getMonthFullDay() {
        Date date = new Date();
        SimpleDateFormat dateFormatYYYYMMDD = new SimpleDateFormat("yyyy-MM-dd");
        List<String> fullDayList = new ArrayList<>(32);
        // 获得当前日期对象
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);
        cal.clear();// 清除信息
//        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month);
        // 1月从0开始
//        cal.set(Calendar.MONTH, month-1 );
        // 当月1号
        cal.set(Calendar.DAY_OF_MONTH, 1);
        int count = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        for (int j = 1; j <= count; j++) {
            fullDayList.add(dateFormatYYYYMMDD.format(cal.getTime()));
            cal.add(Calendar.DAY_OF_MONTH, 1);
        }
        return fullDayList;
    }

    // 获取本周 所有日期（yyyy-mm-dd格式字符串）
    public static List<String> getWeekFullDay() {
        Date date = new Date();
        SimpleDateFormat dateFormatYYYYMMDD = new SimpleDateFormat("yyyy-MM-dd");
        List<String> fullDayList = new ArrayList<>(32);
        // 获得当前日期对象
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.WEEK_OF_MONTH, 0);
        cal.set(Calendar.DAY_OF_WEEK, 2);
        int count = cal.getActualMaximum(Calendar.DAY_OF_WEEK);
        for (int j = 1; j <= count; j++) {
            fullDayList.add(dateFormatYYYYMMDD.format(cal.getTime()));
            cal.add(Calendar.DAY_OF_WEEK, 1);
        }
        return fullDayList;
    }

    /**
     * 通过月份计算季度
     *
     * @param month
     * @return
     */
    public static Integer getQuarter(Integer month) {
        if (month < 1 || month > 12) {
            throw new IllegalArgumentException("输入月份无效");
        }
        return (month - 1) / 3 + 1;
    }
}
